#include "pattern_dialog.h"

#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QPushButton>
#include <QVBoxLayout>

#include "core/music_settings.h"

PatternDialog::PatternDialog(MusicSettings *settings, QWidget *parent):
  QDialog(parent),
  settings(settings) {
  setWindowTitle("Motif");
  QGroupBox *patternBox = new QGroupBox("Motif", this);
  QVBoxLayout *patternBoxLayout = new QVBoxLayout;
  patternBox->setLayout(patternBoxLayout);

  QLabel *infoLabel = new QLabel("<b>U</b> : <i>Up</i><br>"
                                 "<b>D</b> : <i>Down</i><br>"
                                 "<b>R</b> : <i>Repeat</i>", this);
  patternBoxLayout->addWidget(infoLabel);

  pattern = new QLineEdit(this);
  patternBoxLayout->addWidget(pattern);

  // boutons

  QPushButton *okButton = new QPushButton("&Valider", this);
  connect(okButton, SIGNAL(clicked()), this, SLOT(validate()));

  QPushButton *cancelButton = new QPushButton("&Annuler", this);
  connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));

  QHBoxLayout *buttonLayout = new QHBoxLayout;
  buttonLayout->addStretch();
  buttonLayout->addWidget(okButton);
  buttonLayout->addWidget(cancelButton);

  //

  QVBoxLayout *mainLayout = new QVBoxLayout;
  mainLayout->addWidget(patternBox);
  mainLayout->addLayout(buttonLayout);
  setLayout(mainLayout);

  initialize();
}

/*!
 * Initialise les cases en fonction des paramètres
 */
void PatternDialog::initialize() {
  pattern->setText(settings->pattern);
}

/*!
 * Change les paramètres puis ferme la fenêtre
 */
void PatternDialog::validate() {
  QRegExp re("[UDR]*|([UD]\\d+|R)*");
  if(re.exactMatch(pattern->text())) {
    settings->pattern = pattern->text();
    close();
  }
  else {
    QMessageBox::warning(this,
                         "Erreur de motif",
                         "Le motif entré est invalide !");
  }
}
